<template>
  <div>
    <div :style="{margin: '24px 0'}">
      <bread-crumb :module="module" :getRouterPath="getRouterPath" :rootRouterPath="rootRouterPath"></bread-crumb>
    </div>
    <premission-view :module="module" :action="['CREATE']" :style="{marginTop: '8px'}">
      <Button type="primary" @click="modal = !modal">新建</Button>
      <Button :style="{marginLeft: '5px'}">导入</Button>
    </premission-view>
    <data-list :columns="columns" :module="module"></data-list>
    <premission-view :module="module" :action="['CREATE', 'UPDATE']">
      <Modal :title="title" v-model="modal" :closable="false" :mask-closable="false" :footer-hide="false" :loading="loading" @on-ok="handleSubmit('form')" @on-visible-change="handleVisibleChange">
        <Form ref="form" :model="formData" :rules="rules" :label-width="80">
          <FormItem label="名称" prop="name">
            <Input v-model="formData.name" placeholder="请输入"></Input>
          </FormItem>
          <FormItem label="链接">
            <Input v-model="formData.uri" placeholder="请输入"></Input>
          </FormItem>
          <FormItem label="标记">
            <Input v-model="formData.icon" placeholder="请输入"></Input>
          </FormItem>
          <FormItem label="排序" prop="num">
            <!-- <Input v-model.number="formData.num"></Input> -->
            <InputNumber :max="99999" :min="0" v-model="formData.num"></InputNumber>
          </FormItem>
          <FormItem label="备注">
            <Input v-model="formData.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
          </FormItem>
        </Form>
      </Modal>
    </premission-view>
    <premission-view :module="module" :action="['UPDATE']">
      <Modal title="修改父节点" v-model="modalPutParent" :closable="false" :mask-closable="false" :footer-hide="false" :loading="loadingPutParent" @on-ok="handlePutParent">
        <Form :label-width="80">
          <FormItem label="父节点">
            <cas-cader :module="module" projection="MenuWithChildrenCount" :setValue="handleSetValue"></cas-cader>
          </FormItem>
        </Form>
      </Modal>
    </premission-view>
  </div>
</template>

<script>
import CasCader from '@/components/CasCader'
import DataList from '@/components/DataList.vue'
import BreadCrumb from '@/components/BreadCrumb.vue'

import menuApi from '@/api/menu'

export default {
  data () {
    return {
      module: 'menu',
      rootRouterPath: '/setting/menus',
      title: '新建',
      formData: {
        name: '',
        uri: '',
        icon: '',
        num: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称.', trigger: 'blur' }
        ],
        num: [
          { type: 'number', message: '排序必须为十进制数字', trigger: 'blur' }
        ]
      },
      modal: false,
      loading: false,
      modalPutParent: false,
      loadingPutParent: false,
      putParentSelf: null,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '名称',
          key: 'name'
        },
        {
          title: '链接',
          key: 'uri'
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h('div', this.renderActions(h, params))
          }
        }
      ]
    }
  },
  computed: {
    editNode () {
      return this.$store.state[this.module].editNode
    }
  },
  created () {
    console.log('menu created')
  },
  updated () {

  },
  components: {
    CasCader,
    DataList,
    BreadCrumb
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    '$route' (to, from) {
      // 对路由变化作出响应...
      console.log('menu watch $route')
      if (this.$route.params.id) {
        this.$store.dispatch(`${this.module}/setCurNode`, this.$route.params.id)
        this.$store.dispatch(`${this.module}/findByParentId`, {
          page: 0,
          parentId: this.$route.params.id
        })
      } else {
        this.$store.dispatch(`${this.module}/setCurNode`, null)
        this.$store.dispatch(`${this.module}/getList`, {
          page: 0
        })
      }
    }
  },
  methods: {
    getRouterPath (id) {
      return `/setting/menus/${id}/children`
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.loading = true
          const { id, name, uri, icon, num, description, self } = this.formData
          console.log(id, name, uri, icon, num, description)
          if (id) {
            if (name === this.editNode.name && icon === this.editNode.icon && uri === this.editNode.uri && num === this.editNode.num && description === this.editNode.description) {
              this.$Message.info(`${name}无改动`)
              // this.modal = !this.modal
              return
            }
            this.$store.dispatch(`${this.module}/update`, {
              formData: { name, uri, icon, num, description },
              self,
              cb: () => {
                this.$Message.success(`修改${name}成功`)
                this.loading = false
                // this.modal = !this.modal
                // this.$store.dispatch(`${this.module}/reLoad`)
              },
              ecb: () => {
                this.$Message.error(`修改${name}失败`)
                this.loading = false
                // this.$store.dispatch(`${this.module}/reLoad`)
              }
            })
            return
          }
          this.$store.dispatch(`${this.module}/create`, {
            formData: { name, uri, icon, num, description },
            cb: () => {
              this.$Message.success(`添加${name}成功`)
              this.loading = false
              // this.modal = !this.modal
              // this.$store.dispatch(`${this.module}/reLoad`)
            },
            ecb: () => {
              // this.$Message.success(`添加${name}成功`)
              this.$Message.error(`添加${name}失败`)
              this.loading = false
              // this.modal = !this.modal
              // this.$store.dispatch(`${this.module}/reLoad`)
            }
          })
        } else {
          this.$Message.error('Fail!')
        }
      })
    },
    findChildren (index) {
      this.$store.dispatch(`${this.module}/setCurNode`, index)
    },
    show (index) {
      this.title = '编辑'
      this.$store.dispatch(`${this.module}/setEditNode`, index)
      this.formData = {
        id: this.editNode.id,
        name: this.editNode.name,
        uri: this.editNode.uri,
        icon: this.editNode.icon,
        num: this.editNode.num,
        description: this.editNode.description,
        self: this.editNode._links.self.href
      }
      this.modal = !this.modal
    },
    remove (index) {
      this.$store.dispatch(`${this.module}/setEditNode`, index)
      this.$Modal.confirm({
        title: `确定删除${this.editNode.name}`,
        onOk: () => {
          this.$store.dispatch(`${this.module}/remove`, {
            self: this.editNode._links.self.href,
            cb: result => {
              console.log(result)
              this.$Message.success(`删除${this.editNode.name}成功`)
            },
            ecb: error => {
              console.log(error)
              // this.$Message.error(`删除${this.editNode.name}失败`)
              this.$Message.success(`删除${this.editNode.name}成功`)
            }
          })
        }
      })
    },
    putParent (index) {
      this.$store.dispatch(`${this.module}/setEditNode`, index)
      this.modalPutParent = !this.modalPutParent
    },
    handleSetValue (value, selectedData) {
      console.log(value, selectedData)
      if (selectedData && selectedData.length > 0) {
        this.putParentSelf = selectedData[selectedData.length - 1]
      }
    },
    handlePutParent () {
      this.$Modal.confirm({
        title: `修改${this.editNode.name}的父节点为${this.putParentSelf.label}`,
        onOk: () => {
          menuApi.changeParent({
            parent: this.editNode._links.parent.href.substring(0, this.editNode._links.parent.href.indexOf('?') - 1),
            parentSelf: this.putParentSelf.value,
            cb: result => {
              console.log(result)
            },
            ecb: error => {
              console.log(error)
              // this.$Message.error(`删除${cur.name}失败`)
              this.$Message.success(`修改${this.editNode.name}的父节点为${this.putParentSelf.label}成功`)
              this.$store.dispatch(`${this.module}/reLoad`)
            }
          })
        }
      })
    },
    loadChildren (item, callback) {
      item.loading = true
      menuApi.loadChildren({
        self: item.value,
        cb: result => {
          if (!item.children) {
            item.children = []
          }
          for (let i = 0; i < result._embedded.menus.length; i++) {
            if (this.editNode && this.editNode.id && result._embedded.menus[i].id !== this.editNode.id) {
              const node = {
                value: result._embedded.menus[i]._links.self.href,
                label: result._embedded.menus[i].name
              }
              if (result._embedded.menus[i].childrenCount) {
                node.loading = false
                node.children = []
              }
              item.children.push(node)
            }
          }
          item.loading = false
          console.log(item)
          callback()
        }
      })
    },
    handleVisibleChange (visible) {
      if (!visible) {
        this.formData = {
          name: '',
          uri: '',
          icon: '',
          num: 0,
          description: ''
        }
      }
    },
    renderActions (h, params) {
      return [
        h('Button', {
          props: {
            type: 'info',
            size: 'small'
          },
          style: {
            marginRight: '5px'
          },
          on: {
            click: () => {
              console.log(params)
              this.findChildren(params.index)
            }
          }
        }, '子机构'),
        h('PremissionView', {
          props: {
            module: this.module,
            action: ['UPDATE']
          }
        }, [h('Button', {
          props: {
            type: 'success',
            size: 'small'
          },
          style: {
            marginRight: '5px'
          },
          on: {
            click: () => {
              this.show(params.index)
            }
          }
        }, '编辑')]),
        h('PremissionView', {
          props: {
            module: this.module,
            action: ['UPDATE']
          }
        }, [h('Button', {
          props: {
            type: 'warning',
            size: 'small'
          },
          style: {
            marginRight: '5px'
          },
          on: {
            click: () => {
              this.putParent(params.index)
            }
          }
        }, '修改父节点')]),
        h('PremissionView', {
          props: {
            module: this.module,
            action: ['DELETE']
          }
        }, [h('Button', {
          props: {
            type: 'error',
            size: 'small'
          },
          on: {
            click: () => {
              this.remove(params.index)
            }
          }
        }, '删除')])
      ]
    }
  }
}
</script>

<style>
</style>
